<?php
namespace app\wxapplet\controller;

use think\Db;
use think\Request;
use app\yxwadmin\controller\Admin;
use app\common\logic\UploadLogic;
use think\cache\driver\Redis;

/** 
* 图片管理 
*  
* @author      xieliang<xieliang007@qq.com>
* @version     $1.0$ 
* @since       1.0 
*/
class Image extends Admin
{
    public function index()
    {
        return $this->view->fetch('image/index');
    }

    public function getList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');

        $where = array();
        if(!empty($keyword)){
            $where['title']=array('like','%'.$keyword.'%');
        }

        $count = model('ImageModel')->where($where)->count(); //查询满足要求的总记录数
        $list = model('ImageModel')->where($where)->order([$sortName=>$sortOrder])->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function add(){
        if (Request::instance()->isPost()){
            $data=input('post.');
            $baseimage1 = input('post.image_cover1','');
            if(!empty($baseimage1)){
                if(empty($data['image_url'])){
                    $url = explode(',', $baseimage1);
                    $imagetype = '.'.explode("/",explode(';',$url[0])[0])[1];
                    $bdpica = UploadLogic::savepictolocal($url[1],'cst_',$imagetype);
                    $data['image_url'] = $bdpica;
                }
            }
            $data['addtime'] = time();
            $data['updatetime'] = $data['addtime'];

            if($id=model("ImageModel")->allowField(true)->save($data)){                
                $ret["code"]=0;
                $ret['msg']="保存成功";
                return $ret;
            }else{
                $ret["code"]=1;
                $ret['msg']="保存失败";
                return $ret;
            }
        }else{
            return $this->view->fetch('image/add');
        }
    }

    public function edit(){
         //判断提交方式 做不同的处理
         if (Request::instance()->isPost()){            
            $data=input('post.');
            $imgpica = input('post.base64pic','');
            if(!empty($imgpica)){
                if(empty($data['image_url'])){
                    $url = explode(',', $baseimage1);
                    $imagetype = '.'.explode("/",explode(';',$url[0])[0])[1];
                    $bdpica = UploadLogic::savepictolocal($url[1],'cst_',$imagetype);
                    $data['image_url'] = $bdpica;
                }
            }
            $data['updatetime'] = time();
            $res=model('ImageModel')->allowField(true)->save($data,['id' => $data['id']]);
            if($res){
                $appletlist = model('WechatAppletModel')->where("product_code","card_collect")->select();
                $redis = new Redis();
                foreach($appletlist as $applet){
                    $redis_key = "jk_reply_image_".$applet['original_id']."_".$data['id'];
                    $redis->rm($redis_key);
                }
                $ret["code"]=0;
                $ret['msg']="修改成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="修改失败";
            }
            return $ret;
        }else{
            $id = input('get.id');
            $data = model('ImageModel')->find($id);           
            $this->assign('data',$data);
            return $this->view->fetch('image/edit');
        }
    }

    public function del(){
        if ( Request::instance()->isPost() ) {            
            $id = input('post.id/d');
            if ($id > 0) {                
                $res = model('ImageModel')->where('id',$id)->delete();
                if($res){
                    $appletlist = model('WechatAppletModel')->where("product_code","card_collect")->select();
                    $redis = new Redis();
                    foreach($appletlist as $applet){
                        $redis_key = "jk_reply_image_".$applet['original_id']."_".$id;
                        $redis->rm($redis_key);
                    }
                    $ret["code"]=0;
                    $ret['msg']="删除成功";
                }
                else{
                    $ret["code"]=1;
                    $ret['msg']="删除失败";
                }                
            }else{
                $ret["code"]=1;
                $ret['msg']="删除失败,参数错误!";
            }
            return $ret;
        }
    }

    public function group(){
        return $this->view->fetch('image/group');
    }

    public function getgroupList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');

        $where = array();
        if(!empty($keyword)){
            $where['name']=array('like','%'.$keyword.'%');
        }

        $count = model('ImageGroupModel')->where($where)->count(); //查询满足要求的总记录数
        $list = model('ImageGroupModel')->where($where)->order([$sortName=>$sortOrder])->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function addgroup(){
        if (Request::instance()->isPost()){
            $data=input('post.');
            $now = time();            
            Db::startTrans();
            try{
                $imageIds = explode(',',$data['imageIds']);
                //新增分组
                $groupdata['name'] = $data['name'];
                $groupdata['addtime'] = $now;
                $groupdata['updatetime'] = $now;
                $groupid = model("ImageGroupModel")->insertGetId($groupdata);
                if($groupid){                    
                    foreach($imageIds as $image_id){
                        $d['group_id'] = $groupid;
                        $d['image_id'] = $image_id;

                        $ingroupdata[] = $d;
                    }
                }
                $res = model("ImageInGroupModel")->allowField(true)->saveAll($ingroupdata);
                if($res){
                    //提交事务
                    Db::commit();
                    $ret["code"]=0;
                    $ret['msg']="保存成功";
                    return $ret;
                }else{
                    //回滚事务
                    Db::rollback();
                    $ret["code"]=1;
                    $ret['msg']="保存失败";
                    return $ret;
                }
                
            }catch(\Exception $e){
                //回滚事务
                Db::rollback();
                $ret["code"]=1;
                $ret['msg']= $e->getMessage();
                return $ret;
            }            
        }else{
            $list = model("ImageModel")->select();

            $this->assign('list',$list);
            return $this->view->fetch('image/addgroup');
        }
    }

    public function editgroup(){
        //判断提交方式 做不同的处理
        if (Request::instance()->isPost()){
            $data=input('post.');
            $now = time();            
            Db::startTrans();
            try{
                $imageIds = explode(',',$data['imageIds']);
                $res = model("ImageInGroupModel")->where("group_id",$data['id'])->delete();
                if($res){
                    //修改分组
                    $groupdata['name'] = $data['name'];                    
                    $groupdata['updatetime'] = $now;
                    $res = model("ImageGroupModel")->update($groupdata,["id"=>$data['id']]);
                    if($res){                    
                        foreach($imageIds as $image_id){
                            $d['group_id'] = $data['id'];
                            $d['image_id'] = $image_id;

                            $ingroupdata[] = $d;
                        }
                    }
                    $res = model("ImageInGroupModel")->allowField(true)->saveAll($ingroupdata);
                    if($res){
                        //提交事务
                        Db::commit();
                        $ret["code"]=0;
                        $ret['msg']="保存成功";
                        return $ret;
                    }else{
                        //回滚事务
                        Db::rollback();
                        $ret["code"]=1;
                        $ret['msg']="保存失败";
                        return $ret;
                    }
                }else{
                    //回滚事务
                    Db::rollback();
                    $ret["code"]=1;
                    $ret['msg']="删除失败";
                    return $ret;
                }                
            }catch(\Exception $e){
                //回滚事务
                Db::rollback();
                $ret["code"]=1;
                $ret['msg']= $e->getMessage();
                return $ret;
            }
        }else{
            $id = input('get.id');
            $data = model('ImageGroupModel')->find($id);
            $sellist = model("ImageInGroupModel")->field("b.id,b.image_name")->alias('a')->join('Image b','a.image_id=b.id','LEFT')->where("group_id",$id)->select();

            $unsellist = Db::query("SELECT id,image_name FROM crd_image WHERE id NOT IN (SELECT image_id FROM crd_image_in_group WHERE group_id={$id})");

            $this->assign('sellist',$sellist);
            $this->assign('unsellist',$unsellist);
            $this->assign('data',$data);
            return $this->view->fetch('image/editgroup');
        }
    }

    public function delgroup(){
        if ( Request::instance()->isPost() ) {            
            $id = input('post.id/d');
            if ($id > 0) {                
                Db::startTrans();
                try{
                    $res = model("ImageInGroupModel")->where("group_id",$id)->delete();

                    if($res){
                        $res = model('ImageGroupModel')->where('id',$id)->delete();
                        if($res){
                            //提交事务
                            Db::commit();
                            $ret["code"]=0;
                            $ret['msg']="删除成功";
                            return $ret;
                        }else{
                            //回滚事务
                            Db::rollback();
                            $ret["code"]=1;
                            $ret['msg']="删除失败";
                            return $ret;
                        }
                    }else{
                        //回滚事务
                        Db::rollback();
                        $ret["code"]=1;
                        $ret['msg']="删除失败";
                        return $ret;
                    }                
                }catch(\Exception $e){
                    //回滚事务
                    Db::rollback();
                    $ret["code"]=1;
                    $ret['msg']= $e->getMessage();
                    return $ret;
                }       
            }else{
                $ret["code"]=1;
                $ret['msg']="删除失败,参数错误!";
            }
            return $ret;
        }
    }

    public function selImage(){
        return $this->view->fetch('image/selimage');
    }
}